package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {
        try {
            //封装令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            //利用shiro的api来进行登录
            SecurityUtils.getSubject().login(token);
            //获取当前登录用户
            Subject subject = SecurityUtils.getSubject();
            //获取主体的身份信息
            Employee employee = (Employee) subject.getPrincipal();
            if (employee.isStatus()) {
                return new JsonResult();
            } else {
                return new JsonResult(false,"账号已禁用，请联系管理员");
            }

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return new JsonResult(false, "密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "登录异常，请联系管理员");
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        //销毁会话
        session.invalidate();
        //重定向到登录页面
        return  "redirect:/login.html";
    }
}
